package com.MoveEat.Utils;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.protocol.HTTP;

import android.util.Log;


public class Utils
{

	public static final String	BASE_URL	= "http://moveeat.net76.net/API/";
	final static String			TAG			= "[MoveEat]";
	private static final boolean	DEBUG	= true;

	public static String preformRequest(String url)
	{

		HttpGet httpget = new HttpGet(url);
		// httpget.setHeader("MoveEat-Key", Consts.FACEBOOK_APP_SECRET);
		httpget.addHeader("MoveEat-Key", Consts.FACEBOOK_APP_SECRET);
		log(2,"executing request " + httpget.getURI());
		// Create a response handler
		return executeRequest(httpget);
	}

	private static String executeRequest(HttpUriRequest request)
	{
		HttpClient httpclient = new DefaultHttpClient();
		HttpResponse responseBody;
		try
		{
			responseBody = httpclient.execute(request);

			HttpEntity entity = responseBody.getEntity();
			InputStream stream = entity.getContent();
			BufferedReader rd = new BufferedReader(new InputStreamReader(stream), 4096);
			String line;
			StringBuilder sb = new StringBuilder();
			while ((line = rd.readLine()) != null)
			{
				sb.append(line);
			}
			log(2,"response: " + sb.toString());
			return sb.toString();
		}
		catch (ClientProtocolException e)
		{
			e.printStackTrace();
			return null;
		}
		catch (IOException e)
		{
			// TODO Auto-generated catch block
			e.printStackTrace();
			return null;
		}
	}

	public static String preformPostRequest(String url, String payload)
	{
		HttpPost httpPost = new HttpPost(url);
		httpPost.addHeader("MoveEat-Key", Consts.FACEBOOK_APP_SECRET);
		// httpPost.addHeader("Content-Type",
		// "application/x-www-form-urlencoded");
		try
		{
			httpPost.setEntity(new StringEntity(payload, HTTP.UTF_8));
		}
		catch (UnsupportedEncodingException e)
		{
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		log(2,"executing request " + httpPost.getURI());
		return executeRequest(httpPost);

	}

	public static void log(String string)
	{
		Log.i(TAG, string);
	}

	public static void log(int state, String string)
	{

		switch (state)
		{
			case -1:
				Log.e(TAG, string);
				break;

			case 0:
				Log.w(TAG, string);
				break;

			case 1:
				Log.i(TAG, string);
				break;

			case 2:
				if (DEBUG)
				{
					Log.d(TAG, string);
				}
				break;
		}
	}

}
